package ch.bfh.mobicomp.ui.in;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.Timestamp;
import java.util.Date;

import ch.bfh.mobicomp.Mail;
import ch.bfh.mobicomp.R;
import ch.bfh.mobicomp.R.drawable;
import ch.bfh.mobicomp.R.id;
import ch.bfh.mobicomp.R.layout;

public class SettingsActivity extends Activity {

    private static final String tag = "SettingsActivity";
    public static final String SP_KEY_SMS_ALARM = "sms_alarm";
    public static final String SP_KEY_EMAIL_ALARM = "email_alarm";
    public static final String SP_KEY_SMS_NUMBER = "sms_number";
    public static final String SP_KEY_EMAIL_ADDRESS = "email_address";
    private EditText editNumber;
    EditText editEmail;
    CheckBox sms;
    CheckBox email;
    Button saveButton;
    Button mailButton;
    AlertDialog.Builder alertbox;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.settings);

	alertbox = new AlertDialog.Builder(this);
	SharedPreferences pref = getSharedPreferences(AlarmActivity.SP_NAME, MODE_PRIVATE);

	editNumber = (EditText) findViewById(R.id.editText_sms);
	editEmail = (EditText) findViewById(R.id.editText_email);
	sms = (CheckBox) findViewById(R.id.checkBox_sms);
	email = (CheckBox) findViewById(R.id.checkBox_email);
	saveButton = (Button) findViewById(R.id.button_save);
	mailButton = (Button) findViewById(R.id.button_mail);

	this.sms.setOnCheckedChangeListener(new CheckBoxListener());
	this.email.setOnCheckedChangeListener(new CheckBoxListener());

	sms.setChecked(pref.getBoolean(SP_KEY_SMS_ALARM, false));
	email.setChecked(pref.getBoolean(SP_KEY_EMAIL_ALARM, false));
	editNumber.setText(pref.getString(SP_KEY_SMS_NUMBER, ""));
	editEmail.setText(pref.getString(SP_KEY_EMAIL_ADDRESS, ""));

	editNumber.setEnabled(sms.isChecked());
	editEmail.setEnabled(email.isChecked());

	saveButton.setOnClickListener(new SaveButtonClickListener());
	saveButton.setEnabled(true);
	mailButton.setOnClickListener(new MailButtonClickListener());
	mailButton.setEnabled(true);
    }

    private class SaveButtonClickListener implements OnClickListener {

	@Override
	public void onClick(View v) {
	    if (validate()) {
		SharedPreferences pref = getSharedPreferences(AlarmActivity.SP_NAME, MODE_PRIVATE);
		Editor editor = pref.edit();
		editor.putBoolean(SP_KEY_SMS_ALARM, sms.isChecked());
		editor.putBoolean(SP_KEY_EMAIL_ALARM, email.isChecked());
		editor.putString(SP_KEY_SMS_NUMBER, editNumber.getText().toString());
		editor.putString(SP_KEY_EMAIL_ADDRESS, editEmail.getText().toString());
		editor.commit();
		finish();
	    }
	}

	private Boolean validate() {
	    String message = "";
	    Boolean ok = true;
	    Pattern phonePattern = Pattern.compile("^(((\\+41)(\\s?)(\\-?))|(0))([1-9]+)(\\d{1})(\\s?)(\\-?)(\\d{3})(\\s?)(\\-?)(\\d{2})(\\s?)(\\-?)(\\d{2})");
	    Matcher phoneMatcher = phonePattern.matcher(editNumber.getText().toString());

	    if (sms.isChecked() && !phoneMatcher.matches()) {
		message = "Phone number not valid! ";
		ok = false;
	    }

	    Pattern emailPattern = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
	    Matcher emailMatcher = emailPattern.matcher(editEmail.getText().toString());

	    if (email.isChecked() && !emailMatcher.matches()) {
		message += "Email address not valid!";
		ok = false;
	    }

	    if (!ok) {
		alertbox.setTitle("Settings not saved");
		alertbox.setIcon(R.drawable.error);
		alertbox.setMessage(message);
		alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {

		    public void onClick(DialogInterface arg0, int arg1) {
			return;
		    }
		});

		alertbox.show();
	    }

	    return ok;
	}
    }

    private class MailButtonClickListener implements OnClickListener {

	public void onClick(View view) {
	    Log.d(tag, "MAIL_BUTTON pushed");
	    SharedPreferences pref = getSharedPreferences(AlarmActivity.SP_NAME, MODE_PRIVATE);
	    Mail m = new Mail();
	    String[] toArr = {pref.getString(SP_KEY_EMAIL_ADDRESS, "")};
	    m.setTo(toArr);
	    m.setFrom(pref.getString(SP_KEY_EMAIL_ADDRESS, "")); 
//      m.setSubject("THIEF ALARM"); 
//      m.setBody("This Mail was sent, because YOUR PHONE WAS STOLEN."); 

	    try {
//        m.addAttachment("/sdcard/filelocation"); 

		if (m.send()) {
		    Toast.makeText(SettingsActivity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
		    Log.d(tag, "Email sent");
		} else {
		    Toast.makeText(SettingsActivity.this, "Email was not sent.", Toast.LENGTH_LONG).show();
		    Log.d(tag, "Could not send email");
		}
	    } catch (Exception e) {
		Toast.makeText(SettingsActivity.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
		Log.d(tag, "Could not send email", e);
	    }
	}
    }

    private class CheckBoxListener implements OnCheckedChangeListener {

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
	    editNumber.setEnabled(sms.isChecked());
	    editEmail.setEnabled(email.isChecked());
	    //saveButton.setEnabled(sms.isChecked() || email.isChecked());
	}
    }
}